package cn.modfun.common.web;


import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import cn.modfun.common.lang.StringUtils;

public class RequestUtils {

	/**
	 * 判断请求是否为ajax请求
	 * @param request
	 * @return
	 */
	public static boolean isAjax(HttpServletRequest request){
		
		//request.getHeader("accept")!=null && request.getHeader("accept").contains("application/json")
		// 若存在 accept 并且内容为 application/json 就为ajax
		// 若存在 accept 并且内容为 text/html 就为普通请求
		// 若不存在 accept 但存在 X-Requested-With:XMLHttpRequest 就为ajax
		if(((request.getHeader("X-Requested-With") != null || request.getHeader("x-requested-with") != null) && (request.getHeader("X-Requested-With").contains("XMLHttpRequest") || request.getHeader("x-requested-with").contains("XMLHttpRequest")))){
			if(request.getHeader("accept") == null || request.getHeader("accept").contains("application/json")){
				return true;
			}
		}
		if(StringUtils.isNotBlank(request.getParameter("_dataType")) && request.getParameter("_dataType").equals("json")){
			return true;
		}
		return false;
	}
	/**
	 * 获得请求的IP
	 * @param request
	 * @return
	 */
	public static String getIpAddress(HttpServletRequest request) {
		String ipAddress = request.getHeader("x-forwarded-for");
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
			if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
				// 根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
					ipAddress = inet.getHostAddress();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
			}
		}
		// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
															// = 15
			if (ipAddress.indexOf(",") > 0) {
				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
		}
		return ipAddress;
	}
	
	/**
     * 去掉url中的路径，留下请求参数部分
     * @param strURL url地址
     * @return url请求参数部分
     * @author lzf
     */
    private static String TruncateUrlPage(String strURL){
        String strAllParam=null;
        String[] arrSplit=null;
        strURL=strURL.trim().toLowerCase();
        arrSplit=strURL.split("[?]");
        if(strURL.length()>1){
          if(arrSplit.length>1){
              for (int i=1;i<arrSplit.length;i++){
                  strAllParam = arrSplit[i];
              }
          }
        }
        return strAllParam;   
    }
    
    /**
     * 解析出url参数中的键值对
     * 如 "index.jsp?Action=del&id=123"，解析出Action:del,id:123存入map中
     * @param URL  url地址
     * @return  url请求参数部分
     * @author lzf
     */
    public static Map<String, String> urlSplit(String URL){
        Map<String, String> mapRequest = new HashMap<String, String>();
        String[] arrSplit=null;
        String strUrlParam=TruncateUrlPage(URL);
        if(strUrlParam==null){
            return mapRequest;
        }
        arrSplit=strUrlParam.split("[&]");
        for(String strSplit:arrSplit){
              String[] arrSplitEqual=null;         
              arrSplitEqual= strSplit.split("[=]");
              //解析出键值
              if(arrSplitEqual.length>1){
                  //正确解析
                  mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
              }else{
                  if(arrSplitEqual[0]!=""){
                  //只有参数没有值，不加入
                  mapRequest.put(arrSplitEqual[0], "");       
                  }
              }
        }   
        return mapRequest;   
    }
    
    public static void main(String[] args) {
		System.out.println(urlSplit("index.jsp?Action=del&id=123"));
		System.out.println(urlSplit("index.jsp&Action=del&id=123"));
	}
}
